using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Services.Protocols;
using PSLibrary = Microsoft.Office.Project.Server.Library;

namespace MicrosoftFrance.MCS.EPM2007
{
    class ExceptionHandlers
    {
        StreamWriter streamWriter;
        bool writeConsole = true;

        public ExceptionHandlers(StreamWriter sw)
        {
            streamWriter = sw;
        }

        public void HandleSoapException(SoapException ex)
        {
            PSLibrary.PSClientError error = new PSLibrary.PSClientError(ex);
            PSLibrary.PSErrorInfo[] errors = error.GetAllErrors();
            string errMess = "==============================\r\nError: \r\n";
            for (int i = 0; i < errors.Length; i++)
            {
                errMess += "\n" + ex.Message.ToString() + "\r\n";
                errMess += "".PadRight(30, '=') + "\r\nPSCLientError Output:\r\n \r\n";
                errMess += errors[i].ErrId.ToString() + "\n";

                for (int j = 0; j < errors[i].ErrorAttributes.Length; j++)
                {
                    errMess += "\r\n\t" + errors[i].ErrorAttributeNames()[j] + ": "
                       + errors[i].ErrorAttributes[j];
                }
                errMess += "\r\n".PadRight(30, '=');
            }

            WriteConsole(errMess);
        }

        public void HandleWebException(WebException ex)
        {
            string errMess = ex.Message.ToString() + "\n\nLog on, or check the Project Server Queuing Service";
            WriteConsole(errMess);
        }

        public void HandleException(Exception ex)
        {
            WriteConsole(ex.Message);
        }

        public void WriteConsole(string errorMsg)
        {
            if (writeConsole)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error: " + errorMsg);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            AppLog.WriteLine(streamWriter, errorMsg);
        }

        public void ResetConsole()
        {
            Console.ResetColor();
            Console.WriteLine("\r\n\r\nPress any key...");
            Console.ReadKey();
        }
    }
}
